/**
 * @desc
 *
 * @使用场景
 *
 * @author  杨晓东[of1081]
 * @company qianmi.com
 * @Date    16/11/21
 **/
'use strict';
import 'whatwg-fetch'
 let webApi = module.exports={};

/**
 * 向环境中部署包信息
 * @param name    npm包名称
 * @param version npm包版本
 * @param envCode 将要部署的环境编码
 */
webApi.deployTpl=  async function ({name,version,envCode,syncTemplate}) {
 let result  = await fetch('/tpl/deploy',{
  method: 'post',
  credentials: 'include',
  headers: {
   'Content-Type': 'application/json'
  },
  body:JSON.stringify({name,version,envCode,syncTemplate})
 });
 result = await result.json();
 return result;
}


/**
 * 重新打包环境中的模板
 * @param envCode
 * @returns {Promise.<*>}
 */
webApi.rebuildTpl=  async function ({envCode}) {
    let result  = await fetch('/tpl/buildAll',{
        method: 'post',
        credentials: 'include',
        headers: {
            'Content-Type': 'application/json'
        },
        body:JSON.stringify({envCode})
    });
    result = await result.json();
    return result;
}

/**
 * 获取所有可用包列表
 * @return {*}
 */
webApi.getAllpackage = async function (){

 let result  = await fetch('/tpl/packages',{});
 result = await result.json();

 if(result.result ==='ok'){
   return result.data;
 } else {
  throw new Error(result.message);
 }
}


/**
 * 获取一个包的所有版本信息
 * @param pageageName
 * @return {*}
 */
webApi.getPackageVersions = async function ({pageageName}){
 //真接从NPM服务器拿相关信息
 let result  = await fetch('http://registry.npm.qianmi.com/'+pageageName,{pageageName});
 result = await result.json();

 return result;
}

/**
 * 获取日志信息
 * @param envCode
 * @param projectName
 * @param pageSize
 * @param pageNum
 * @returns {*}
 */
webApi.getPublishLogs = async function ({envCode,projectName,pageSize,pageNum}) {
 let result  = await fetch('/resources/getLogs',{
  method: 'post',
  headers: {
   'Content-Type': 'application/json'
  },
  body:JSON.stringify({envCode,projectName,pageSize,pageNum})
 });
 result =  await result.json();

 return result;
}

webApi.getVersionHistories = async function ({name,pageSize,pageNum}) {
 let result = await fetch('/resources/getVersionHistories', {
  method: 'post',
  headers:{
   'Content-Type': 'application/json'
  },
  body:JSON.stringify({name,pageSize,pageNum})
 });
 result = await result.json();

 return result;
}
